<script setup>
import { apiHome as getDevicesTreeBaseApi } from '@/api/index.js'
import { onMounted, ref } from 'vue'

const treeData = ref([])
const defaultSelectKey = ref('')
const defaultSelectKeyObj = ref({})
const selectedParentNodes = ref([])
const switchNode = (code, node) => {
  defaultSelectKey.value = code
  const parentNodes = getAllParents(treeData.value, code)
  selectedParentNodes.value = parentNodes
  $emit('onChange', code, node, parentNodes)
}
const getDevicesTreeData = async () => {
  defaultSelectKey.value = ''
  const res = await getDevicesTreeBaseApi.getDevicesTree()
  const data = res.data.map((item) => {
    if (item.satellites) {
      item.satellites = item.satellites.map((satellite) => {
        if (!Object.prototype.hasOwnProperty.call(satellite, 'twoline')) {
          satellite.twoline = ''
        }
        return satellite
      })
    }
    return item
  })
  const tempTreeData = JSON.parse(
    JSON.stringify(data, null, 2).replace(/("satellites":|"subsystems":|"devices":)/gi, '"children":')
  )
  const getChildren = (data = []) => {
    return data.map((item) => {
      item.key = item.code
      if (item.deviceId && !defaultSelectKey.value) {
        defaultSelectKey.value = item.key
        defaultSelectKeyObj.value = item
        selectedParentNodes.value = getAllParents(treeData.value, item.key)
      }
      if (item.children) {
        item.children = getChildren(item.children)
      }
      return item
    })
  }
  getChildren(tempTreeData)
  treeData.value = tempTreeData
}
const getAllParents = (tree, targetCode) => {
  const parents = []

  const findParents = (nodes, parentCodes) => {
    for (const node of nodes) {
      if (node.code === targetCode) {
        parents.push(...parentCodes)
        return true // 找到目标节点
      }
      const newParentCodes = [...parentCodes, node] // 更新父节点路径
      if (findParents(node.children || [], newParentCodes)) {
        return true // 如果在子节点中找到目标节点
      }
    }
    return false // 未找到目标节点
  }

  findParents(tree, [])
  return parents
}

const $emit = defineEmits(['onChange', 'onLoad'])
onMounted(() => {
  getDevicesTreeData().then(() => {
    $emit('onLoad', treeData.value, defaultSelectKeyObj.value, selectedParentNodes.value)
  })
})
</script>

<template>
  <a-card title="" class="h-[calc(100vh-150px)]">
    <template #title>
      <slot name="card-title" />
    </template>

    <div class="h-[calc(100vh-240px)] overflow-y-auto">
      <a-tree
        block-node
        show-line
        :data="treeData"
        v-if="defaultSelectKey"
        :default-selected-keys="[defaultSelectKey]"
        :default-expand-all="true"
      >
        <template #title="nodeData">
          <slot
            name="title"
            :nodeData="nodeData"
            :switchNode="switchNode"
            :value="defaultSelectKey"
            :selectedParentNodes="selectedParentNodes"
          ></slot>
        </template>
        <template #extra="nodeData">
          <slot
            name="extra"
            :nodeData="nodeData"
            :switchNode="switchNode"
            :value="defaultSelectKey"
            :selectedParentNodes="getAllParents(treeData, nodeData.code)"
          ></slot>
        </template>
      </a-tree>
    </div>
  </a-card>
</template>

<style scoped lang="less"></style>
